<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
include_once BASEPATH.'libraries/Upload.php';

/**
 * 
 */
class UploadFiles extends CI_Upload {
	//instancia de codeniter
	protected $CI;
	
	function __construct() {
		parent::__construct();
		$this->CI =& get_instance();
	}
	
	/**
	 * $params = array(
	 * 		'file' => '', //url de la imagen a cargar o nombre del parametro $_FILE
			'img_temp' => FALSE, //si es una url = false, si es nombre de $_File = true
			'size' => array('big','medium','small', '50x50'), //almenos uno de ellos ordenados de esa forma	
	 		'mime' => true  //Indica de donde obtener la extencion de la imagen. Si es true la obtendra usando el mime. Opcional
	 * );
	 */
	public function uploadFile($params){
		//si es un $_File o si es una Url
		if($params['img_temp'] == FALSE){ //si es una Url
			$file_temp = UploadFile::pathTemp().$this->copyExternalFile($params['file'], (isset($params['mime'])? $params['mime']: false));
			if($file_temp == FALSE)
				return FALSE;
		}else{ //si es un $_File
			$config = array(
				'upload_path' 		=> UploadFile::pathTemp(),
				'allowed_types' 	=> 'gif|jpg|png',
				'max_size' 			=> '800',
				'encrypt_name'		=> TRUE
			);
			
			$this->initialize($config);
			if($this->do_upload($params['file']) == FALSE)
				return FALSE;
			$res_upload = $this->data();
			$file_temp = UploadFile::pathTemp().$res_upload['file_name'];
		}
		
		$res = $this->uploadExternalImg($file_temp, $params);
		$this->deleteFile($file_temp);
		return $res;
	}
	
	/**
	 * Usando una imagen local (ubicada en temp) redimenciona y coloca las nuevas
	 * imagenes en las carpetas correspondientes a los tamaños seleccionados
	 */
	protected function uploadExternalImg($source, $params){
		$this->CI->load->library('image_lib');
		$config = array(
			'image_library' 	=> 'gd2',
			'source_image' 		=> $source,
			'new_image' 		=> '',
			'create_thumb' 		=> FALSE,
			'maintain_ratio' 	=> FALSE,
			'width' 			=> 0,
			'height' 			=> 0
		);
		
		$source = str_replace(UploadFile::pathTemp(), '', $source);
		$result = array();
		
		$paths = UploadFile::pathAll();
		$urls = UploadFile::urlsAll();
		foreach($params['size'] as $key => $itm) {
			if(isset($paths[$itm])){
				$n_path = $paths[$itm];
				$size 	= explode('x', UploadFile::${$itm.'_size'});
				$n_url	= $urls[$itm];
			}else{
				$n_path = UploadFile::pathOtros();
				$size 	= explode('x', $itm);
				$n_url	= UploadFile::urlOtros();
			}
			
			$config['new_image'] 	= $n_path.$source;
			$config['width'] 		= $size[0];
			if($size[1] == 0)
				$config['maintain_ratio'] = TRUE;
			else
				$config['height'] 		= $size[1];
			
			$this->CI->image_lib->clear();
			$this->CI->image_lib->initialize($config);
			$this->CI->image_lib->resize();
			
			$result[$itm] = array(
				'url' 		=> $n_url.$source,
				'path' 		=> $n_path.$source,
				'type'		=> $this->get_extension($source),
				'width' 	=> $config['width'],
				'height' 	=> $config['height'],
			);
		}
		
		return $result;
	}
	
	/**
	 * Copia un archivo de cualquier dominio al servidor en la carpeta temps
	 */
	private function copyExternalFile($source, $mime=false){
		if($mime)
			$info_img = getimagesize($source);
		
		$file_name = md5(microtime().rand()).
					($mime? '.'.UploadFile::getImgType($info_img["mime"]): $this->get_extension($source));
		
		$source = str_replace(Sys::$url_base, '', $source);
		if(copy($source, UploadFile::pathTemp().$file_name)){
			return $file_name;
		}
		return FALSE;
	}
	
	/**
	 * Elimina un archivo del servidor
	 */
	public function deleteFile($path){
		$path = str_replace(Sys::$url_base, '', $path);
		return unlink($path);
	}
}
?>